package com.xms.security.identity;

import com.xms.core.org.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 当前登录用户
 * </p>
 *
 * @author migo
 * @since 2021/9/5
 */
@Service
public class CurrentUser implements ICurrentUser {
    private IAuthenticationService _authenticationService;

    @Autowired
    public void CurrentUser(IAuthenticationService authenticationService) {
        _authenticationService = authenticationService;
    }

    @Override
    public HttpServletRequest getRequest() {
        //如果是异步线程，这里会取不到
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        //return ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
    }

    @Override
    public UserContext getUser() {
        return _authenticationService.getAuthenticatedUser(getRequest());
    }

    @Override
    public boolean isAdministrator() {
        return this.getUser() != null ? this.getUser().IsSuperAdmin : false;
    }

    @Override
    public List<UUID> getRoles() {
        UserContext userContext = this.getUser();
        if (userContext != null) {
            return userContext.roles;
        }
        return null;
    }

    @Override
    public String getSessionId() {
        return _authenticationService.getId(getRequest());
    }
}
